package org.sample.vm.classloading;

public class ByteUtils {
	
	public static int bytes2Int(byte[] bytes, int start, int length) {
		int sum = 0;
		int end = start + length;
		for (int i = start; i < end; i++) {
			int n = ((int) bytes[i]) & 0xff;
			n <<= (--length) * 8;
			sum = n + sum;
		}
		return sum;
	}
	
	public static byte[] int2Bytes(int value, int length) {
		byte[] bytes = new byte[length];
		for (int i = 0; i < length; i++) {
			bytes[length - i - 1] = (byte) ((value >> 8 * i) & 0xff);
		}
		return bytes;
	}
	
	public static String bytes2String(byte[] bytes, int start, int length) {
		return new String(bytes, start, length);
	}
	
	public static byte[] string2Bytes(String str) {
		return str.getBytes();
	}
	
	public static byte[] bytesReplace(byte[] bytes, int offset, int length, byte[] replaceBytes) {
		byte[] replacedBytes = new byte[bytes.length + (replaceBytes.length - length)];
		System.arraycopy(bytes, 0, replacedBytes, 0, offset);
		System.arraycopy(replaceBytes, 0, replacedBytes, offset, length);
		System.arraycopy(bytes, offset + length, replacedBytes, offset + replaceBytes.length, bytes.length - offset - length);
		return replacedBytes;
	}

}
